﻿using IapService.Entity;
using NHibernate.Criterion;

namespace IapService.Data
{
    public class InstanceData : Data<Instance>
    {
        public Instance Get(int id)
        {
            Instance item;
            using (var session = Session)
            {
                item = session.Get<Instance>(id);

                var instanceReport = session.CreateCriteria<InstanceReport>()
                    .Add(Restrictions.Eq("InstanceId", item.Id))
                    .UniqueResult<InstanceReport>()
                    ;
                if(instanceReport != null)
                    item.Report = instanceReport.Report;
            }
            return item;
        }

        public new Instance Remove(Instance item)
        {
            ClientInstance clientInstance;
            using (var session = Session)
            {
                clientInstance = session.CreateCriteria<ClientInstance>()
                    .Add(Restrictions.Eq("Instance.Id", item.Id))
                    .UniqueResult<ClientInstance>()
                    ;
            }
            var result = new ClientInstanceData().Remove(clientInstance);
            return result.Instance;
        }

        public new Instance Save(Instance item)
        {
            var needAddNewReport = item.Id == 0;
            using (var session = Session)
            {
                session.SaveOrUpdate(item);

                if(needAddNewReport)
                {
                    var report = new Report();
                    session.SaveOrUpdate(report);
                    var instreport = new InstanceReport();
                    instreport.InstanceId = item.Id;
                    instreport.Report = report;
                    session.SaveOrUpdate(instreport);
                }

                session.Flush();
            }
            return item;
        }
    }
}